import * as mqtt from "mqtt/dist/mqtt.min";
import storage from "@/utils/storage";

const state = {
  MQTT_CILENT: null,
  MQTT_CONNECT_STATUS: false,
  tpcs: [],
  newMessageList: [],
  newMessageOutObj: {},
};
const getters = {
  newMessageListGetter: (state) => state.newMessageList,
  newMessageOutObjGetter: (state) => state.newMessageOutObj,
};
const actions = {
  // 创建MQTT 连接
  MQTT_CONNECT({ commit }, obj) {
    commit("MQTT_CONNECT", obj);
  },
  // 取消订阅
  MQTT_CANCEL_TOPIC({ commit }, obj) {
    commit("MQTT_CANCEL_TOPIC", obj);
  },

  // 添加 MQTT 订阅
  MQTT_NEW_TOPIC({ commit }, obj) {
    commit("MQTT_NEW_TOPIC", obj);
  },
  // 关闭mqtt
  MQTT_END({ commit }, obj) {
    commit("MQTT_END", obj);
  },
};
const mutations = {
  MQTT_CONNECT_ADD_MESSAGE(state, message) {
    if (message.outTime) {
      state.newMessageOutObj = message;
    } else {
      if (state.newMessageList.length >= 6) {
        state.newMessageList.pop();
      }
      state.newMessageList.unshift(message);
    }
  },
  MQTT_END(state, data) {
    state.newMessageList = [];
    state.MQTT_CILENT.end();
  },

  MQTT_CONNECT(state) {
    const userInfo = storage.get("userInfo");
    const url = process.env.VUE_APP_MQTT_URL + "/" + userInfo.parkCode;
    state.MQTT_CILENT = mqtt.connect(url, {
      clientId: "family_park_client-" + new Date().getTime(),
      clean: true,
      useSSL: false,
      username: process.env.VUE_APP_MQTT_USER, // 用户名,WS不用传
      password: process.env.VUE_APP_MQTT_PASS,
      connectTimeout: 5 * 1000,
      reconnectPeriod: 3 * 1000,
    });

    console.log("MQTT 开始连接！");

    state.MQTT_CILENT.on("connect", () => {
      console.log("MQTT 连接成功！");
      state.MQTT_CONNECT_STATUS = true;
    });

    state.MQTT_CILENT.onMessageArrived = (message) => {
      console.log("订阅断开" + message.payloadString);
      state.MQTT_CONNECT_STATUS = false;
    };

    //重连监听
    state.MQTT_CILENT.on("reconnect", (error) => {
      console.log("正在重接", error);
    });

    // 连接断开后触发的回调
    state.MQTT_CILENT.on("close", function (error) {
      console.log("已断开连接", error);
    });

    state.MQTT_CILENT.on("message", (topic, message) => {
      console.log(topic, message);
      message = message.toString();
      message = JSON.parse(message);
      if (message.outTime) {
        state.newMessageOutObj = message;
      } else {
        state.newMessageList = state.newMessageList.filter(
          (item) => item.carNo != message.carNo
        );
        if (state.newMessageList.length >= 6) {
          state.newMessageList.pop();
        }
        state.newMessageList.unshift(message);
      }
    });

    state.MQTT_CILENT.on("error", (err) => {
      console.log(err, 111);
      if (!state.isErr) {
        state.isErr = true;
        setTimeout(async () => {
          // if (!state.connectStatus && this.userInfo) {
          //   await MessageBox.confirm(
          //     "链接断开，需要刷新页面，是否继续？",
          //     "提示",
          //     {
          //       confirmButtonText: "确定",
          //       cancelButtonText: "取消",
          //       type: "warning",
          //     }
          //   );
          //   router.go(0);
          // }
        }, 30 * 60 * 1000);
      }
    });
  },

  MQTT_CANCEL_TOPIC(state, data) {
    state.MQTT_CILENT.unsubscribe(data, function (err) {});
  },
  MQTT_NEW_TOPIC(state, data) {
    state.MQTT_CILENT.subscribe(data, {
      qos: 2,
    });
    state.tpcs.push(data);
  },
};

export default {
  name: "mqtt",
  state,
  getters,
  actions,
  mutations,
};
